package presentation.converters;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import business.BusinessObjectAssembler;
import business.CommonLogic;
import business.exception.BusinessException;

import persistence.LibraryLocation;

public class LibraryLocationConverter implements Converter {
	
	private static CommonLogic commonLogic;
	
	static {
		commonLogic = BusinessObjectAssembler.getCommonLogic();
	}

	@Override
	public Object getAsObject(FacesContext fctx, UIComponent comp, String value)
			throws ConverterException {
		Object retVal = null;		
		if (value != null && ConverterUtil.isNumber(value)) {
			try {
				for (LibraryLocation location : commonLogic.getAllLibraryLocations()) {
					if(location.getId()==Integer.valueOf(value)) {
						retVal = location;
					}
				}
			}
			catch (BusinessException be) {
				//TODO: create FacesMessage
			}			
		}
		return retVal;
	}

	@Override
	public String getAsString(FacesContext fctx, UIComponent comp, Object value)
			throws ConverterException {
		String retVal = null;
		LibraryLocation location = (LibraryLocation) value;
		if (location != null) {
			retVal = String.valueOf(location.getId());
		}
		return retVal;
	}

}